<template>
    <div v-bind="$attrs">
        <el-space v-if="cols.length > 0 || $slots.action" wrap>
            <template v-for="col in cols2" :key="col.code">
                <el-tree-select v-if="col.control=='combo' && isTreeSelect(col.options)" 
                    :disabled="isDisabled(col)"
                    :style="{width: getWidth(col)}" 
                    check-strictly    
                    :placeholder="'请选择'+col.label"
                    clearable
                    :tree="{clearable:true}"
                    v-model="search[col.code]" 
                    :data="col.options">
                </el-tree-select>
                <el-select :placeholder="getPlaceholder(col)" v-else-if="col.control == 'combo' || col.control == 'radio'" v-model="search[col.code]"
                    v-bind="col.combo" 
                    :style="{width: getWidth(col)}" 
                    :disabled="isDisabled(col)">
                    <el-option v-if="col.searchAll != false" :label="'-' + col.label + '-'" value=""></el-option>
                    <template v-if="isSelectGroup(col.options)">
                        <el-option-group v-for="group in selectGroups(col.options)" :label="group.label"
                            :key="group.label">
                            <el-option v-for="item in group.items" :label="item.label" :value="item.value"
                                :key="item.value"></el-option>
                        </el-option-group>
                    </template>
                    <template v-else>
                        <el-option v-for="item in col.options" :label="item.label" :value="item.value"
                            :key="item.value"></el-option>
                    </template>
                </el-select>
                <el-date-picker :placeholder="getPlaceholder(col)" v-else-if="col.control == 'date'" 
                    :disabled="isDisabled(col)"
                    :style="{width: getWidth(col,'140px')}" 
                    v-model="search[col.code]" 
                    v-bind="col.date"></el-date-picker>
                <MyTime2 v-else-if="col.control=='MyTime2'" 
                    :disabled="isDisabled(col)"
                    v-model="search[col.code]" 
                    :style="{width: getWidth(col,'140px')}" 
                    v-bind="col.MyTime2"></MyTime2>
                <my-select :placeholder="getPlaceholder(col)" v-else-if="col.control == 'select'" :options="col.options"
                    :style="{width: getWidth(col,'140px')}" 
                    :disabled="isDisabled(col)"
                    v-model="search[col.code]" v-bind="col.select" :title="col.label" allowEmpty
                    :formData="search">
                </my-select>
                <template v-else-if="col.control == 'selectinput'">
                    <!--<span>{{col.selectinput}}</span>-->
                    <my-select-input :placeholder="getPlaceholder(col)" v-model="search[col.code]" :formData="search"
                        :disabled="isDisabled(col)"
                        v-bind="col.selectinput" 
                        :style="{width: getWidth(col,'140px')}" ></my-select-input>
                </template>
                <template v-else-if="col.control == 'hidden'">
                    <component v-if="isCusComponent(col.control2)" :is="col.control2" :ref="'ref_'+col.code"
                        :disabled="isDisabled(col)"
                        v-model="search[col.code]" :placeholder="getPlaceholder(col)" v-bind="col[col.control2]"
                        style="width:0px;height: 0px;visibility: hidden;" />
                </template>
                <MyCheckBox3 v-else-if="col.control == 'check' || col.control == 'MyCheckBox3'" v-model="search[col.code]"
                    :disabled="isDisabled(col)"
                    v-bind="col.check" >{{ col.label }}</MyCheckBox3>

                <el-input-number v-else-if="col.control=='number'" v-bind="col.number" v-model="search[col.code]" :disabled="isDisabled(col)" />

                <el-input :placeholder="getPlaceholder(col)"
                    :disabled="isDisabled(col)"
                    v-else-if="col.control == 'text' || col.control == 'textarea'" v-model="search[col.code]"
                    v-bind="col.text || col.textarea" 
                    :style="{width: getWidth(col,'120px')}" ></el-input>

                <component v-else-if="isCusComponent(col.control)" :is="col.control" v-model="search[col.code]" 
                    :disabled="isDisabled(col)"
                    :placeholder="getPlaceholder(col)" v-bind="col[col.control]" :formData="search" style="max-width: 250px" />
                    
                <el-input :placeholder="getPlaceholder(col)" v-else v-model="search[col.code]" 
                    :style="{width: getWidth(col,'120px')}" 
                    :disabled="isDisabled(col)">
                </el-input>
            </template>
            <el-button v-if="cols.length > cols2.length" type="default" @click="onMoreSearch">...</el-button>
            <el-button v-if="cols.length > 0" type="default" @click="onSearch">检索</el-button>
            <slot name="action"></slot>
        </el-space>

        <my-search-dlg ref="dlgSearch" :tbname="tbname" @search="doSearch" :excludeSearch="excludeSearch"></my-search-dlg>
    </div>
</template>

<script>

import { ElForm, ElFormItem, ElButton, ElSelect, ElTreeSelect, ElOption, ElDatePicker, ElCheckbox, ElInput } from 'element-plus'
import { resolveComponent } from 'vue';
import { Utils } from './main';

export default {
    name: "MySearchBar",
    components: { ElForm, ElFormItem, ElButton, ElSelect, ElTreeSelect, ElOption, ElDatePicker, ElCheckbox, ElInput },
    props: {
        maxSearchItem: Number,
        tbname: String,
        modelValue: Object,
        excludeSearch: String//排除在外的搜索字段
    },
    emits: ["update:modelValue", "clickSearch"],
    mounted() {
        this.loadConfig();
    },
    data() {
        return {
            search: {},
            cols: [],
            cols2: [], //最多只显示两个搜索条件
        };
    },
    created(){
        this.search = {...this.modelValue};
    },
    methods: {
        isCusComponent(cmpName) {
            let cmp = resolveComponent(cmpName);
            return typeof (cmp) == "object";
        },
        loadConfig() {
            if (this.tbname == "") return;
            this.$server.getDM(this.tbname).then((res) => {
                let msearch = { ...this.modelValue };
                let sfields = (Utils.getTbSearchFields(res, msearch) || []).filter(p=>p.control!='hidden');

                sfields = sfields.filter(p => p != null);
                if (this.excludeSearch) {
                    let ee = this.excludeSearch.replaceAll(",",";").split(";").filter(p => p.length > 0);
                    sfields = sfields.filter(p => ee.indexOf(p.code) == -1);
                }
                this.cols = sfields;
                var max = this.maxSearchItem || this.$store.maxSearchItem || (this.$mbh5 ? 2 : 8);
                if (sfields.length > max) {
                    this.cols2 = sfields.slice(0, max);
                } else {
                    this.cols2 = sfields;
                }
                this.search = { ...msearch, ...this.search };
                this.$emit("update:modelValue", this.search);
            });
        },
        getLabel(col) {
            // if (["combo", "select", "check","selectinput","datetime","date","text"].indexOf(col.control) != -1) {
            //     return "";
            // }
            // return col.label;
            return "";
        },
        getPlaceholder(col) {
            return col.placeholder || col.label || "";
        },
        onMoreSearch() {
            this.$refs.dlgSearch.open(this.search);
        },
        onSearch() {
            var param = { ...this.modelValue, ...this.search, ____key: (new Date()).getTime() };
            this.$emit("update:modelValue", param);
            this.$emit("clickSearch", param);
        },
        doSearch(search) {
            this.search = { ...search };
            this.onSearch();
        },
        isSelectGroup(options) {
            return options && options.length > 0 && options[0].group;
        },
        selectGroups(ops) {
            let groups = {};
            ops.forEach(p => {
                let key = p.group || "";
                groups[key] = groups[key] || [];
                groups[key].push(p);
            });
            return Object.keys(groups).map(key => {
                return { label: key, items: groups[key] }
            });
        },
        isTreeSelect(options){
            return options && options.length > 0 && options[0].children;
        },
        isDisabled(col){
            return col.editable==false;
        },
        getWidth(col, defaultWidth){
            return col.width || defaultWidth || "140px" ;
        }
    },
    watch: {
        tbname: function (newValue) {
            this.loadConfig();
        },
        modelValue:{
            handler(newVal){
                this.search = { ...newVal };
            },
            deep:true
        },
        search(newValue){
        }
    },
};
</script>

<style>
.el-form--inline .el-form-item {
    margin-right: 8px !important;
}
</style>